import { ReactElement, useRef, useState, useEffect } from 'react'
import { Modal, Form, FormInstance, Select, message, Alert } from 'antd'
import Text from '@src/components/text'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { CaseSimpleSchema, getCaseSimpleList, copyRequest } from './ajax'
import { awaitWrap } from '@js/tool'

const { Item } = Form
const { Option } = Select

async function initCaseList (setCases: (v: CaseSimpleSchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getCaseSimpleList())
  if (e === null && d instanceof Array) {
    setCases(d)
  }
}

async function submitHandle (d: { [k: string]: any }, caseDescs: string[], cases: CaseSimpleSchema[], hide: () => void, refreshData: () => void): Promise<void> {
  const targetids: string[] = d.targetids
  const data = {
    sourceid: d.sourceid,
    targetids: targetids.map(li => {
      const index = caseDescs.indexOf(li)
      return cases[index].id
    })
  }
  const h = message.loading('提交中')
  const [e] = await awaitWrap(copyRequest(data))
  h()
  if (e === null) {
    message.success('同步成功').then(null, null)
    refreshData()
    hide()
  }
}

interface Props {
  visible: boolean
  data: CaseSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, data, hide, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [cases, setCases] = useState<CaseSimpleSchema[]>([])
  const [caseDescs, setCaseDescs] = useState<string[]>([])
  const initialValues = data !== null ? { caseno_desc: data.caseno_desc, sourceid: data.id } : {}
  useEffect(() => {
    initCaseList(setCases).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    setCaseDescs(cases.map(li => li.caseno_desc))
  }, [cases])
  useEffect(() => {
    const c = formRef.current
    if (data !== null && c !== null) {
      c.setFieldsValue({ sourceid: data.id, caseno_desc: data.caseno_desc })
    }
  }, [data, formRef])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  return (
    <Modal visible={visible} title='同步案件信息' onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} initialValues={initialValues} onFinish={async d => await submitHandle(d, caseDescs, cases, hide, refreshData)}>
        <Item name='sourceid' noStyle><span /></Item>
        <Alert type='warning' showIcon message='确认后把【源案件】考核信息同步到【目标案件】中' style={{ marginBottom: '24px' }} />
        <Item label='源案件' name='caseno_desc'>
          <Text />
        </Item>
        <Item label='目标案件' name='targetids' rules={[{ required: true, message: '目标案件不能为空' }]}>
          <Select placeholder='请选择' showSearch mode='multiple'>
            {cases.map((li, i) => <Option key={i} value={li.caseno_desc}>{li.caseno_desc}</Option>)}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
